package com.yjf.ljr.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.yjf.ljr.R;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.util.Base64;
import com.yjf.ljr.util.ImageUtils;
import com.yjf.ljr.util.WebJavaScriptInterface;
import com.yjf.ljr.view.PhotoDialog;

public class AdvActivity extends IjActivity {

	private WebView mWvContent;
	private String mHttpUrl = null;
	private String mAdvTitle = null;
	private boolean mIsLoad = true;
	private ValueCallback<Uri> mUploadMessage;
	private final static int FILECHOOSER_RESULTCODE = 1;
	private String photoName;
	private int cropSize;
	private String index;
	private String appCacheDir;

	@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);

		mHttpUrl = getIntent().getStringExtra("advUrl");
		mAdvTitle = getIntent().getStringExtra("advTitle");
		if (TextUtils.isEmpty(mAdvTitle)) {
			findViewById(R.id.title_bar).setVisibility(View.GONE);
		} else {
			((TextView)findViewById(R.id.tv_title)).setText(mAdvTitle);
			findViewById(R.id.btn_title_left).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					AdvActivity.this.finish();
				}
			});
		}
		mWvContent = (WebView) findViewById(R.id.wvUniversity_schoollife);

		WebSettings settings = mWvContent.getSettings();
		mWvContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		settings.setSupportZoom(false);
		settings.setBuiltInZoomControls(false);
		settings.setDomStorageEnabled(true);
		settings.setAppCacheMaxSize(1024 * 1024 * 9);// 设置缓冲大小
		appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
		settings.setAppCachePath(appCacheDir);
		settings.setAllowFileAccess(true);
		settings.setAppCacheEnabled(true);
		settings.setJavaScriptEnabled(true);
		settings.setCacheMode(WebSettings.LOAD_DEFAULT);
		mWvContent.addJavascriptInterface(new JavaScriptInterface(), "bornClient");
		mWvContent.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				showProgressDialog();
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				mWvContent.setVisibility(View.GONE);
				mIsLoad = false;
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				dismissProgressDialog();
				// mWvContent.loadUrl("javascript:callback();");
				if (mIsLoad) {
					mWvContent.setVisibility(View.VISIBLE);
					super.onPageFinished(view, url);
				} else {
					mWvContent.setVisibility(View.GONE);
				}
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					startActivity(intent);
				} else {
					view.loadUrl(url);
				}
				return true;
			}
		});

		mWvContent.setWebChromeClient(new WebChromeClient() {
			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
				mUploadMessage = uploadMsg;
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
				mContext.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"), FILECHOOSER_RESULTCODE);
			}

			public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
				mUploadMessage = uploadMsg;
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
				mContext.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"), FILECHOOSER_RESULTCODE);
			}

			// Android < 3.0 调用这个方法
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				mUploadMessage = uploadMsg;
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.addCategory(Intent.CATEGORY_OPENABLE);
				intent.setType("image/*");
				mContext.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"), FILECHOOSER_RESULTCODE);
			}
		});

		CookieSyncManager.createInstance(this);
		mWvContent.loadUrl(mHttpUrl);
	}

	private void photoFinish(String path) {
		String base64str;
		try {
			base64str = encodeBase64File(path);
			String str = "javascript:saveFile('" + base64str + "', '" + index + "');";
			mWvContent.loadUrl(str);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(mContext, "选择文件出错,请稍后再试", Toast.LENGTH_SHORT).show();
		}
		cropSize = 0;
	}

	public static String encodeBase64File(String path) throws Exception {
		File file = new File(path);
		FileInputStream inputFile = new FileInputStream(file);
		byte[] buffer = new byte[(int) file.length()];
		inputFile.read(buffer);
		inputFile.close();
		return Base64.encode(buffer);
	}

	private int clearCacheFolder(File dir, long numDays) {
		int deletedFiles = 0;
		if (dir != null && dir.isDirectory()) {
			try {
				for (File child : dir.listFiles()) {
					if (child.isDirectory()) {
						deletedFiles += clearCacheFolder(child, numDays);
					}

					if (child.lastModified() < numDays) {
						if (child.delete()) {
							deletedFiles++;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return deletedFiles;
	}

	@Override
	protected void onDestroy() {
		CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(mContext);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		// context.deleteDatabase("webview.db");
		// context.deleteDatabase("webviewCache.db");
		// mWvContent.clearCache(true);
		// mWvContent.clearHistory();
		// mWvContent.clearFormData();
		// mWvContent.pauseTimers();
		mWvContent.setWebViewClient(new WebViewClient());
		super.onDestroy();
	}

	@Override
	@SuppressLint("NewApi")
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == FILECHOOSER_RESULTCODE) {
			if (null == mUploadMessage)
				return;
			Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
			mUploadMessage.onReceiveValue(result);
			mUploadMessage = null;
		} else if (requestCode == CommonData.PHOTOHRAPH && resultCode == RESULT_OK) {
			String path = PhotoDialog.mFilePath + CommonData.USERID + "1.jpg";
			photoName = "family_" + new Date().getTime() + ".jpg";
			path = ImageUtils.bitmap2File(path, photoName);
			/*
			 * File picture = new File(path); if (!picture.exists()) { try {
			 * picture.createNewFile(); } catch (IOException e) {
			 * e.printStackTrace(); } } startPhotoZoom(Uri.fromFile(picture));
			 */
			if (cropSize > 0) {
				startPhotoZoom(Uri.parse(path));
			} else {
				photoFinish(PhotoDialog.mFilePath + photoName);
			}
		} else if (requestCode == CommonData.PHOTORESOULT1) {
			Bundle extras = intent.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				File file = new File(PhotoDialog.mFilePath + photoName);
				try {
					FileOutputStream out = new FileOutputStream(file);
					if (photo.compress(Bitmap.CompressFormat.PNG, 100, out)) {
						out.flush();
						out.close();
						photoFinish(PhotoDialog.mFilePath + photoName);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public class JavaScriptInterface extends WebJavaScriptInterface {

		public void startBrowser(String url) {
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			Uri content_url = Uri.parse(url);
			intent.setData(content_url);
			startActivity(intent);
		}

		public void finish() {
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					mContext.finish();
				}
			});
		}

		public void logout() {
			CommonData.USERID = "";
		}

		public void startCamera(String index) {// 默认为完整照片
			// new PhotoDialog(context).show();
			AdvActivity.this.index = index;
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(PhotoDialog.mFilePath, CommonData.USERID + "1.jpg")));
			mContext.startActivityForResult(intent, CommonData.PHOTOHRAPH);
			cropSize = 0;
		}

		public void startCamera(String cropSize, String index) {
			startCamera(index);
			try {
				AdvActivity.this.cropSize = Integer.valueOf(cropSize);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 显示截取框
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, CommonData.IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", cropSize);
		intent.putExtra("outputY", cropSize);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, CommonData.PHOTORESOULT1);
	}

	@Override
	public void onBackPressed() {
		if (null != mWvContent && mWvContent.canGoBack()) {
			mWvContent.goBack();
		} else {
			finish();
		}
	}

}
